<template>
  <div class="box-content">
    <div class="navigation">人群分析</div>
    <!--搜索-->
    <div class="mt-3">
      <el-row>
        <el-col :span="12">
          <!--<el-button type="primary" size="small" @click="onSearch">查询</el-button>-->
          <!--<el-button type="primary" size="small" @click="create.dialogFormVisible = true">新增</el-button>-->
        </el-col>
      </el-row>
    </div>
    <!--表格-->
    <div class="mt-3">
      <el-table
              :data="userData"
              v-loading="loading"
              align="center"
              :element-loading-text="loadText"
              :header-cell-style="tableHeaderColor"
              stripe
              style="width: 100%">
        <el-table-column
                prop="id"
                align="center"
                label="编号"
                width="100"
        >
        </el-table-column>
        <!--<el-table-column-->
                <!--prop="name"-->
                <!--align="center"-->
                <!--label="用户"-->
        <!--&gt;-->
        <!--</el-table-column>-->
        <el-table-column
                prop="name"
                align="center"
                label="下载文件"
        >
        </el-table-column>
        <el-table-column
                prop="tr_name"
                align="center"
                label="景区名称"
        >
        </el-table-column>
        <!--<el-table-column-->
                <!--prop="isUpload"-->
                <!--align="center"-->
                <!--label="数据"-->
        <!--&gt;-->
        <!--</el-table-column>-->
        <el-table-column
                label="添加时间"
                align="center"
                width="160">
          <template slot-scope="scope">
            <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(0, 11):'无'}}</div>
            <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(11 ):'无'}}</div>
          </template>
        </el-table-column>
        <el-table-column
                label="修改时间"
                align="center"
                width="160">
          <template slot-scope="scope">
            <div align="center">{{scope.row['updated_at']?scope.row['updated_at'].slice(0, 11):'无'}}</div>
            <div align="center">{{scope.row['updated_at']?scope.row['updated_at'].slice(11 ):'无'}}</div>
          </template>
        </el-table-column>
        <el-table-column
                label="操作"
                align="center"
                fixed="right"
                width="160">
          <template slot-scope="scope">
            <el-button
                    size="mini"
                    type="primary"
                    @click="handleUpload(scope.row)">导入
            </el-button>

            <!--<el-button-->
                    <!--size="small"-->
                    <!--type="warning"-->
                    <!--@click="handleExport(scope.row)">导出-->
            <!--</el-button>-->
            <a :href=" 'http://c.yueshengkj.com/api/download?id=' + scope.row.id"  style="margin-left: 6px">导出</a>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-3 float-right">
        <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageInfo.current_page"
                :page-size="pageInfo.per_page"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageInfo.total">
        </el-pagination>
      </div>
    </div>
    <!--新增对话框-->
    <el-dialog title="新增"
               :visible.sync="create.dialogFormVisible"
               :close-on-click-modal="false"
               width="600px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="负责人姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入负责人姓名" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="负责人手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入负责人手机号" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入登录密码" style="width: 450px;"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" style="width: 450px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="create.dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" :loading="create.loadingCreate"
                   @click="submitCostomer('form')">{{create.loadingCreate?'创建中':'点击创建'}}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
            title="文件上传"
            :visible.sync="upload.dialogUpload"
            :close-on-click-modal="false"
            width="500px"
    >
      <div style="text-align: center" v-loading="upload.loadingUpload" element-loading-text="文件上传中，请勿关闭">
        <el-upload
                class="upload-demo"
                drag
                action="123"
                :before-upload="beforeAvatarUpload"
                :onError="uploadError"
                :onSuccess="uploadSuccess">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx文件</div>
        </el-upload>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button v-on:click="upload.dialogUpload = false">取 消</el-button>
        <el-button type="primary" v-on:click="upload.dialogUpload = false">确 定</el-button>
      </div>
    </el-dialog>　　
  </div>
</template>

<script>
    import axios from 'axios';
    export default {
        name: "crowdAnalysis",
        data() {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    var r = /^[^\u4e00-\u9fa5]+$/
                    if (!r.test(value)) {
                        callback(new Error('密码不能为中文!'));
                    }
                    if (value.length < 6) {
                        callback(new Error('密码长度在 6 到 18 个字符!'));
                    }
                    callback();
                }
            };
            var validateName = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入姓名'));
                } else {
                    callback();
                }
            };
            var phoneValid = (rule, value, callback) => {
                let phoneReg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
                if (!value) {
                    callback(new Error('请输入手机号'))
                }
                if (!phoneReg.test(value)) {
                    callback(new Error('请输入正确的手机号码'))
                }
                callback()
            };
            return {
                pageInfo: {
                    per_page: 10,
                    total: 0,
                    current_page: 1
                },
                loadText: '数据加载中',
                userData: [
                    {
                        id: 1,
                        name: '北普陀山景区',
                        file_name: '15928585007.txt',
                        isUpload: '未上传',
                        update_at: '2019.02.23 10:10:10',
                        created_at: '2019.02.22 10:10:10'
                    }
                ],
                searchStr: '',
                search: {},
                loading: false,
                create: {
                    loadingCreate: false,
                    dialogFormVisible: false,
                },
                upload: {
                    dialogUpload: false,
                    uploadId: null,
                    loadingUpload: false,
                },
                form: {
                    name: '',
                    phone: '',
                    email: '',
                    password: ''
                },
                rules: {
                    name: [
                        {required: 'true', message: '请输入姓名', trigger: 'change'}
                    ],
                    phone: [
                        {validator: phoneValid, trigger: 'change'}
                    ],
                    password: [
                        {validator: validatePass, trigger: 'change'}
                    ],
                    email: [
                        {type: 'email', message: '请输入正确的邮箱地址', trigger: 'change'}
                    ]
                }
            }
        },
        watch: {
            dialogFormVisible: function (val) {
                if (!val) {
                    Object.keys(this.form).forEach(key => this.form[key] = '');
                    this.$refs['form'].resetFields();
                }
            }
        },
        created() {
            this.getAccountList();

        },
        methods: {
            getAccountList() {
                this.loading = true;
                this.$http.get('api/auth/crowdFiles' + this.searchStr, {
                    params: {
                        pageSize: this.pageInfo.per_page,
                        page: this.pageInfo.current_page
                    }
                })
                    .then((result) => {
                        if (result.status_code == 200) {
                            this.userData = result.data.data;
                            this.pageInfo.total = result.data.total;
                        }
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            onSearch() {
                this.searchStr = "";
                if (this.search.inputName) {
                    this.addConStr();
                    this.searchStr += `id=${this.search.inputName}`;
                }
                this.pageInfo.current_page = 1;
                this.getAccountList();
            },
            addConStr() {
                if (this.searchStr.length > 0) {
                    this.searchStr += '&';
                } else {
                    this.searchStr += '?';
                }
            },
            submitCostomer(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                    } else {
                        return false;
                    }
                });
            },
            handleUpload(val) {
                this.upload.uploadId = val.id;
                this.upload.dialogUpload = true;
            },
            beforeAvatarUpload (file) {
                let fileName=new Array();
                fileName =file.name.split('.');
                const extension = fileName[fileName.length-1] === 'xlsx';
                if (!extension) {
                    this.$message({
                        message: '上传模板只能是xlsx格式!',
                        type: 'warning'
                    });
                }
                if (extension) {
                    let fd = new FormData();
                    fd.append('id', this.upload.uploadId);
                    fd.append('file', file);
                    this.newImport(fd);
                }
                return false;
            },
            newImport (data) {
                let config = {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Authorization' : 'Bearer' + localStorage.getItem('token')
                    }
                };
                this.upload.loadingUpload = true;
                axios.post(process.env.VUE_APP_API_HOST + 'api/auth/uploadCrowdFiles', data,config)
                    .then((res) => {
                        if (res.data.status_code == 200) {
                            this.$message({
                                type: 'success',
                                message: res.data.msg,
                                during:1000
                            });
                            this.upload.loadingUpload = false;
                            this.upload.dialogUpload = false;
                            this.getAccountList();
                        } else {
                            this.$message.warning(res.data.msg);
                        }

                    })
                    .catch((err) => {
                        this.upload.loadingUpload = false;
                        this.upload.dialogUpload = false;
                        // this.$message.warning(err.response.msg || "数据异常，请重试");
                    })
            },
            uploadSuccess (response) {
                let code = response.returncode;
                let msg = response.msg;
                this.open(msg, code);
            },
            // 上传错误
            uploadError (response) {
                this.open("500", "文件导入异常！");
            },
            handleExport(val) {
                // window.location.href =  val.path;
                this.$http.get('api/download',{
                    params:{
                        id: val.id
                    }
                })
                    .then((result) => {
                        if (result.status_code == 200) {

                        }
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            handleSizeChange(val) {
                this.pageInfo.current_page = 1;
                this.pageInfo.per_page = val;
                this.getAccountList();
            },
            handleCurrentChange(val) {
                this.pageInfo.current_page = val;
                this.getAccountList();
            },
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #FAFAFA;color: #000;font-weight: 500;height:54px;font-size:14px'
                }
            },
        }
    }
</script>

<style lang="less" scoped>

</style>